#include	"Shell.h"
#include	<windows.h>
#include	<gl/gl.h>
#include	<gl/glu.h>

const float Shell::DEFAULT_SPEED = 4.0f;
const float Shell::SIZE = 0.3f;

Shell::Shell(Map * map, Facing facing, const Vector2i & spawn, float distance, bool players)
	:	m_speed(DEFAULT_SPEED)
	,	m_distance(distance)
	,	m_active(true)
	,	m_facing(facing)
	,	m_spawn(spawn)
	,	m_map(map)
	,	m_players(players)
{
}

void Shell::update(double delay)
{
	if(m_active)
	{
		m_distance += float(m_speed * delay);
		Vector2i pos = m_spawn;
		switch(m_facing)
		{
		case left:
			pos[0] -= int(m_distance + SIZE / 2 + 0.5f);
			break;
		case right:
			pos[0] += int(m_distance - SIZE / 2 + 0.5f);
			break;
		case up:
			pos[1] -= int(m_distance + SIZE / 2 + 0.5f);
			break;
		case down:
			pos[1] += int(m_distance - SIZE / 2 + 0.5f);
			break;
		}
		if(m_map->isWall(pos))
		{
			m_map->destroyWall(pos);
			m_active = false;
		}
	}
}

void Shell::render() const
{
	if(m_active)
	{
		glMatrixMode(GL_MODELVIEW);
		glPushMatrix();
			Vector2f pos(getPos());
			glPushAttrib(GL_CURRENT_BIT  | GL_ENABLE_BIT);
				glDisable(GL_TEXTURE_2D);
				glDisable(GL_COLOR_MATERIAL);
				glEnable(GL_BLEND);
				glEnable(GL_DEPTH_TEST);
				glEnable(GL_CULL_FACE);
				Vector2f mapSize = m_map->getMapSize();
				glTranslatef(
					-mapSize[0] / 2 + pos[0] + 0.5f,
					+mapSize[1] / 2 - 1.0f - pos[1],
					-m_map->getDepth() + 1.0f
					);
				glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
				glBegin(GL_QUADS);
					glVertex3f(0.0f, -SIZE / 2, 0.0f);
					glVertex3f(SIZE / 2, 0.0f, 0.0f);
					glVertex3f(0.0f, SIZE / 2, 0.0f);
					glVertex3f(-SIZE / 2, 0.0f, 0.0f);
				glEnd();
			glPopAttrib();
		glPopMatrix();
	}
}

Vector2f Shell::getPos() const
{
	Vector2f pos = m_spawn;
	switch(m_facing)
	{
	case left:
		pos[0] -= m_distance;
		break;
	case right:
		pos[0] += m_distance;
		break;
	case up:
		pos[1] -= m_distance;
		break;
	case down:
		pos[1] += m_distance;
		break;
	}
	return pos;
}

bool Shell::isActive() const
{
	return m_active;
}

bool Shell::isPlayers() const
{
	return m_players;
}

